package cn.ug.analyse.mq;

import cn.ug.analyse.bean.request.MemberAnalyseMsgParamBean;
import cn.ug.analyse.service.MemberAnalyseService;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.ensure.Ensure;
import cn.ug.feign.MemberUserService;
import cn.ug.member.bean.response.MemberUserBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static cn.ug.config.QueueName.QUEUE_MEMBER_ANALYSE;


/**
 * 会员数据分析
 * @auther ywl
 */
@Component
@RabbitListener(queues = QUEUE_MEMBER_ANALYSE)
public class MemberAnalyseReceiver {

    private Log log = LogFactory.getLog(MemberAnalyseReceiver.class);

    @Resource
    private MemberAnalyseService  memberAnalyseService;

    @Resource
    private MemberUserService memberUserService;

    private ObjectMapper mapper = new ObjectMapper();



    @RabbitHandler
    public void process(MemberAnalyseMsgParamBean paramBean) {
        try {

            log.info("-----会员分析消息发送开始------");
            log.info(mapper.writeValueAsString(paramBean));
            log.info("--------传递的过来参数----------会员="+ paramBean.getMemberId()+"---------类型="+paramBean.getType());

            //校验参数
            Ensure.that(paramBean == null).isTrue("00000002");
            Ensure.that(paramBean.getMemberId()).isNull("");
            Ensure.that(paramBean.getType()).isNull("19000402");

            //获取会员渠道id
            if(StringUtils.isNotBlank(paramBean.getMemberId())){
                SerializeObject<MemberUserBean> obj = memberUserService.findById(paramBean.getMemberId());
                if(obj.getCode() == ResultType.NORMAL) {
                    MemberUserBean memberUserBean = obj.getData();
                    paramBean.setChannelId(memberUserBean.getChannelId());
                    log.info("----获取到的渠道id---"+memberUserBean.getChannelId());
                }
            }

            memberAnalyseService.addMemberAnalyse(paramBean);
            log.info("-----会员分析消息发送结束------");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
